/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool Find(TreeNode* root,TreeNode* p)
    {
        if(root==nullptr)
            return false;
        return root==p || Find(root->left,p) || Find(root->right,p);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

        if(root==p || root==q || root==nullptr)
            return root;
        bool pleft=Find(root->left,p);
        bool qleft=Find(root->left,q);
        if(pleft && qleft)
        {
            return lowestCommonAncestor(root->left,p,q);
        }
        else if(pleft || qleft)
        {
            return root;
        }
        else{
            return lowestCommonAncestor(root->right,p,q);
        }
    }
};
